package com.koron.css2.clientCenter.impl;

import com.koron.css2.ImportExcelInterface;
import com.koron.css2.baseConfig.bean.PrefStrategyBean;
import com.koron.css2.baseConfig.bean.TradeClassifyBean;
import com.koron.css2.baseConfig.bean.WaterTypeBean;
import com.koron.css2.baseConfig.mapper.*;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.bean.UserOpenBean;
import com.koron.css2.clientCenter.mapper.*;
import com.koron.css2.common.dto.HeaderInfoDto;
import com.koron.css2.meterService.bean.query.MsInfoQueryBean;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.*;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.mapper.TWaterCompanyMapper;
import com.koron.css2.serviceManage.mapper.UserFieldConfigMapper;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;

public class OpenUserImport implements ImportExcelInterface {



	@Override
	public MessageBean<?> importExel(SessionFactory factory, UserInfoBean userInfo, RequestBean req,
			List<Map<String, String>> data, MultipartFile file) {
		
		MessageBean<?> msg = MaptoObjct(factory, userInfo,data);
		return msg;
	}

	@Override
	public List<HeaderInfoDto> getHeaderInfo(UserInfoBean userInfo) {
		List<HeaderInfoDto> headerInfos = new ArrayList<HeaderInfoDto>();
		List<UserFieldBean> listUserFieldBean = ADOConnection.runTask("_default", factory -> {
			UserFieldConfigMapper mapper = factory.getMapper(UserFieldConfigMapper.class);
			List<UserFieldBean> tem = mapper.findFieldNameByPageNameAndGroupCode("OpenAccount", userInfo.getCurWaterCode());
			return tem;
		}, List.class);

		headerInfos.add(new HeaderInfoDto("客户证件号码", true, "certNo"));
		headerInfos.add(new HeaderInfoDto("客户名称", true, "ctmName"));
		headerInfos.add(new HeaderInfoDto("客户结构化地址", true, "clientAddr"));
		headerInfos.add(new HeaderInfoDto("客户单元地址", true, "clientAddrDetail"));
		headerInfos.add(new HeaderInfoDto("客户类型", true, "ctmType"));
		headerInfos.add(new HeaderInfoDto("证件类型", true, "certType"));
		headerInfos.add(new HeaderInfoDto("信用等级", true, "creditLevel"));
		headerInfos.add(new HeaderInfoDto("固定电话", true, "linkTel"));
		headerInfos.add(new HeaderInfoDto("手机号码", true, "mobile"));
		headerInfos.add(new HeaderInfoDto("传真号码", true, "faxNumber"));
		headerInfos.add(new HeaderInfoDto("缴费方式", true, "payWay"));
		headerInfos.add(new HeaderInfoDto("账户类型", true, "accountType"));
		headerInfos.add(new HeaderInfoDto("投递方式", true, "deliverWay"));
		headerInfos.add(new HeaderInfoDto("投递地址", true, "deliverAddr"));
		headerInfos.add(new HeaderInfoDto("电子邮件", true, "emailAddr"));
		headerInfos.add(new HeaderInfoDto("单位名称", true, "invoiceTitle"));
		headerInfos.add(new HeaderInfoDto("纳税人识别号", true, "invoiceTax"));
		headerInfos.add(new HeaderInfoDto("联系地址", true, "invoiceAddr"));
		headerInfos.add(new HeaderInfoDto("座机号码", true, "invoiceLink"));
		headerInfos.add(new HeaderInfoDto("开户银行", true, "invoiceBank"));
		headerInfos.add(new HeaderInfoDto("银行账户", true, "invoiceAccount"));
		headerInfos.add(new HeaderInfoDto("增值税标记", true, "vatFlag"));
		headerInfos.add(new HeaderInfoDto("预开票标记", true, "preInvoicing"));
		headerInfos.add(new HeaderInfoDto("合并开票标记", true, "mergeInvoicing"));

		/**
		 * 动态标题头字段填入
		 */
		for (UserFieldBean userFieldBean:listUserFieldBean){
			if (("装表地址").equals(userFieldBean.getFieldName())){
				headerInfos.add(new HeaderInfoDto("装表结构化地址", true, "clientContractAddr"));
				headerInfos.add(new HeaderInfoDto("装表单元地址", true, "clientContractAddrDetail"));
				continue;
			}
			headerInfos.add(new HeaderInfoDto(userFieldBean.getFieldName(), true, userFieldBean.getFieldCode()));
		}
		headerInfos.add(new HeaderInfoDto("用水类型", true, "useWaterType"));
		headerInfos.add(new HeaderInfoDto("优惠策略", true, "prefStrategyId"));
		headerInfos.add(new HeaderInfoDto("优惠证件号码", true, "prefCertNo"));
		headerInfos.add(new HeaderInfoDto("优惠策略开始日期", true, "prefBeginDate"));
		headerInfos.add(new HeaderInfoDto("优惠策略结束日期", true, "prefEndDate"));
		return headerInfos;
	}

	@Override
	public boolean isCheckHeader() {
		// TODO Auto-generated method stub
		return true;
	}
	public  MessageBean<?> MaptoObjct(SessionFactory factory,UserInfoBean userInfoBean,List<Map<String, String>> data) {
		//数据字典
		Map<String, String> CTT = Tools.mapDicByCode(factory, "CTT");//客户类型
		Map<String, String> CDL = Tools.mapDicByCode(factory, "CDL");//信用等级
		Map<String, String> IDT = Tools.mapDicByCode(factory, "IDT");//证件类型
		Map<String, String> BPW = Tools.mapDicByCode(factory, "BPW");//缴费方式
		Map<String, String> CTL = Tools.mapDicByCode(factory, "CTL");//装表位置
		Map<String, String> ACT = Tools.mapDicByCode(factory, "ACT");//账户类型
		Map<String, String> SDW = Tools.mapDicByCode(factory, "SDW");//投递方式
		Map<String, String> UWS = Tools.mapDicByCode(factory, "UWS");//用水对象
		Map<String, String> CMC = Tools.mapDicByCode(factory, "CMC");//水表用途
		BankMapper bankeMapper = factory.getMapper(BankMapper.class);
		DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
		
		OpenUserMapper mapper = factory.getMapper(OpenUserMapper.class);
		UserInfoMapper userMapper = factory.getMapper(UserInfoMapper.class);
		AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
		CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
		TWaterCompanyMapper twmapper = factory.getMapper(TWaterCompanyMapper.class,"_default");
		//获取水司设置的code
		//String adminAreaDivi = twmapper.selectCompanyByCode(userInfoBean.getCurWaterCode());
		PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class,"_default");
		BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
		TradeClassifyMapper tradeMapper = factory.getMapper(TradeClassifyMapper.class);
		WaterTypeMapper waterTypeMapper = factory.getMapper(WaterTypeMapper.class);
		PrefStrategyMapper prefStrategyMapper = factory.getMapper(PrefStrategyMapper.class);
		MsInfoMapper msMapper = factory.getMapper(MsInfoMapper.class, DBSourceUtils.getDbEnv(userInfoBean.getCurWaterCode()));
		List<AccountInfoBean> accountList = new ArrayList<AccountInfoBean>();//存账户信息，一条sql保存
		List<CtmInfoBean> ctmList = new ArrayList<CtmInfoBean>();//存客户信息，一条sql保存
		List<UserBean> userList = new ArrayList<UserBean>();//存用户信息，一条sql保存
		List<UserOpenBean> openTempList = new ArrayList<UserOpenBean>();//存userOpenTemp信息，一条sql保存
		List<Map<String, String>> returnMap = new ArrayList<Map<String,String>>();
		
		List<Map<String, String>> errorMap = new ArrayList<Map<String,String>>();
		Map<String,CtmInfoBean> certNo = new HashMap<String, CtmInfoBean>();
		Map<String,String> meterNomap = new HashMap<String, String>();
		AccountInfoBean accountInfo = null;
		CtmInfoBean ctmInfo = null ;
		UserBean userInfo = null;
		for (Map<String, String> map : data) {
			accountInfo = new AccountInfoBean();
			ctmInfo = new CtmInfoBean();
			userInfo = new UserBean();
			// 获取用户信息
			userInfo.setUserNo(Tools.getBillNo(factory, "USER_INFO", userInfoBean.getCurWaterCode()));
			//MsInfoDto msInfo = new MsInfoDto();
			UserOpenBean userOpenInfo = new UserOpenBean();
			String errorMsg = "";
//			List<CtmInfoBean> oltCtm = ctmMapper.querySameClient(map.get("certNo"),1);
//			if(oltCtm.size()>0) {
//				BeanUtils.copyProperties(oltCtm.get(0),ctmInfo);
//			}else if(!"".equals(map.get("certNo")) && certNo.get(map.get("certNo"))!=null){
//				BeanUtils.copyProperties(certNo.get(map.get("certNo")),ctmInfo);
//			}else {
			ctmInfo.setCtmNo(Tools.getSameCtmNo(userInfo.getUserNo()));
			ctmInfo.setCertNo(map.get("certNo"));
			ctmInfo.setCtmName(map.get("ctmName"));
			ctmInfo.setCtmAddr(map.get("ctmAddr"));
			String ctmType = getKey(CTT, map.get("ctmType"));
			if(ctmType!=null) {
				ctmInfo.setCtmType(ctmType);//客户类型
			}else {
				errorMsg=errorMsg+"客户类型不存在;";
			}
			String certType = getKey(IDT, map.get("certType"));
			if(certType!=null) {
				ctmInfo.setCertType(certType);//证件类型
			}else {
				errorMsg=errorMsg+"证件类型不存在;";
			}
			String creditLevel =getKey(CDL, map.get("creditLevel"));
			if(creditLevel!=null) {
				ctmInfo.setCreditLevel(creditLevel);//信用等级
			}
			ctmInfo.setLinkTel(map.get("linkTel"));
			ctmInfo.setMobile(map.get("mobile"));
			ctmInfo.setFaxNumber(map.get("faxNumber"));

			certNo.put(ctmInfo.getCertNo(), ctmInfo);
//			}
			ctmInfo.setCreateInfo(userInfoBean);
			
			if(!StringUtils.isEmpty(map.get("accountNo"))) {
				AccountInfoBean oldAccount = accountMapper.getAccountInfoByCode(map.get("accountNo"), 1);
				if(oldAccount!=null) {
					accountInfo=oldAccount;
					//根据账户编号查客户信息，账户信息不允许同时存在于两个客户底下
					CtmInfoBean ctmInfoBean = ctmMapper.getCtmByAccountNo(accountInfo.getAccountNo());
					BeanUtils.copyProperties(ctmInfoBean,ctmInfo);
				}else {
					errorMsg=errorMsg+"账户编号不存在;";
				}
			}else {
				String payWay = getKey(BPW, map.get("payWay"));
				if(payWay!=null) {
					accountInfo.setPayWay(payWay);//缴费方式
				}else {
					errorMsg=errorMsg+"缴费方式不存在;";
				}
				String deliverWay = getKey(SDW, map.get("deliverWay"));
				if(deliverWay!=null) {
					accountInfo.setDeliverWay(deliverWay);//投递方式
				}else {
					errorMsg=errorMsg+"投递方式不存在;";
				}
				String accountType = getKey(ACT, map.get("accountType"));
				if(accountType!=null) {
					accountInfo.setAccountType(accountType);//账户类型
				}else {
					errorMsg=errorMsg+"账户类型不存在;";
				}
				
//				// 获取开户行名称
//				if (!StringUtils.isBlank(map.get("openAccountBank"))) {
//					BankBean bankName = bankeMapper.findBankByName(map.get("openAccountBank"));//开户银行
//					if(bankName!=null && bankName.getId()!=null) {
//						accountInfo.setOpenAccountBank(bankName.getId());
//					}else {
//						errorMsg=errorMsg+"开户银行不存在;";
//					}
//				}
				accountInfo.setOpenAccountName(map.get("openAccountName"));
				accountInfo.setBankAccount(map.get("bankAccount"));
				accountInfo.setEntrustNo(map.get("entrustNo"));
				accountInfo.setEntrustContract(map.get("entrustContract"));
				accountInfo.setDeliverAddr(map.get("deliverAddr"));
				accountInfo.setEmailAddr(map.get("emailAddr"));
				if (!StringUtils.isBlank(map.get("vatFlag"))) {
					if("是".equals(map.get("vatFlag"))) {
						accountInfo.setVatFlag("1");
					}else {
						accountInfo.setVatFlag("0");
					}
				}else {
					accountInfo.setVatFlag("0");
				}
				/*
				String invoiceType = getKey(BBT, map.get("invoiceType"));
				if(invoiceType!=null) {
					accountInfo.setInvoiceType(invoiceType);//发票类型
				}else {
					errorMsg=errorMsg+"发票类型不存在;";
				}*/
				/**
				 * 预开票转换
				 */
				if (map.containsKey("preInvoicing") && StringUtils.isNotEmpty(map.get("preInvoicing"))){
					if (("是").equals(map.get("preInvoicing"))){
						accountInfo.setPreInvoicing(1);
					}else {
						accountInfo.setPreInvoicing(0);
					}
				}
				/**
				 * 合并开票转换
				 */
				if (map.containsKey("mergeInvoicing") && StringUtils.isNotEmpty(map.get("mergeInvoicing"))){
					if (("是").equals(map.get("mergeInvoicing"))){
						accountInfo.setMergeInvoicing(1);
					}else {
						accountInfo.setMergeInvoicing(0);
					}
				}

				accountInfo.setInvoiceTitle(map.get("invoiceTitle"));
				accountInfo.setInvoiceTax(map.get("invoiceTax"));
				accountInfo.setInvoiceAddr(map.get("invoiceAddr"));
				accountInfo.setInvoiceLink(map.get("invoiceLink"));
				//银行账户
				accountInfo.setInvoiceBank(map.get("invoiceBank"));
				accountInfo.setInvoiceAccount(map.get("invoiceAccount"));
				accountInfo.setAccountNo(Tools.getSameAccountNo(userInfo.getUserNo()));
			}
			accountInfo.setCreateInfo(userInfoBean);
			userInfo.setHouseCert(map.get("houseCert"));
			userInfo.setContractNo(map.get("contractNo"));
			userInfo.setContractAddr(map.get("contractAddr"));
			userInfo.setContractDate(map.get("contractDate"));
			userInfo.setUseTimeLimit(map.get("useTimeLimit"));
			if (StringUtils.isBlank(userInfo.getUseTimeLimit())) {
				userInfo.setUseTimeLimit(null);
			}
			// 获取行政区域
			/*
			if (!StringUtils.isEmpty(map.get("adminArea"))) {
				DistrictBean name = districtMapper.findDistrictByName(map.get("adminArea"));
				if(name!=null && name.getId()!=null) {
					userInfo.setAdminArea(name.getId());
				}else {
					errorMsg=errorMsg+"行政区域不存在;";
				}
			}else {
				errorMsg=errorMsg+"行政区域不能为空;";
			}
			 */
			// 获取营业区域
			if (!StringUtils.isEmpty(map.get("businessArea"))) {
				//将传过来的营业区域先保存
				String id = businessAreaMapper.findBusinessAreaByName(map.get("businessArea"), userInfoBean.getCurWaterCode());
				if(!StringUtils.isEmpty(id)) {
					userInfo.setBusinessAreaName(userInfo.getBusinessArea());
					userInfo.setBusinessArea(id);
					//获取配置参数，是否取营业区域默认册本号
					String dbEnv = DBSourceUtils.getDbEnv(userInfoBean.getCurWaterCode());
					String on_off = Tools.getConfigValue(dbEnv, "DEFAULT_BOOK_NO_ON_OFF");
					if("1".equals(on_off)) {
						BusinessAreaBean business = businessAreaMapper.findBusinessAreaInfoById(id);
						userInfo.setBookNo(business.getBookNo());
					}
				}else {
					errorMsg=errorMsg+"营业区域不存在;";
				}
			}else {
				errorMsg=errorMsg+"营业区域不能为空;";
			}
			// 获取行业分类名称
			
			if (!StringUtils.isEmpty(map.get("tradeClassify"))) {
				TradeClassifyBean tradeClassify = tradeMapper.selectTradeClassifyByName(map.get("tradeClassify"));
				if(tradeClassify!=null) {
					userInfo.setTradeClassify(tradeClassify.getId());
				}else {
					errorMsg=errorMsg+"行业分类不存在;";
				}
			}
			userInfo.setStopWaterLinkMan(map.get("stopWaterLinkMan"));
			userInfo.setStopWaterLinkMobile(map.get("stopWaterLinkMobile"));
			userInfo.setComments(map.get("comments"));
			//userInfo.setBookNo(map.get("bookNo"));
			if (StringUtils.isBlank(map.get("lastReadingNum"))) {
				userInfo.setLastReadingNum(0);
			} else {
				userInfo.setLastReadingNum(Integer.parseInt(map.get("lastReadingNum")));
			}
			/*
			if(StringUtils.isNotBlank(map.get("sortNo"))) {
				userInfo.setSortNo(Integer.parseInt(map.get("sortNo")));
			}
			String meterReadingCycle = getKey(RTP, map.get("meterReadingCycle"));
			if(meterReadingCycle!=null) {
				userInfo.setMeterReadingCycle(meterReadingCycle);//抄表周期
			}else {
				errorMsg=errorMsg+"抄表周期不存在;";
			}*/
			/*String meterType = getKey(WMT, map.get("meterType"));
			if(meterType!=null) {
				userInfo.setMeterType(meterType);//水表类型
			}else {
				errorMsg=errorMsg+"水表类型不存在;";
			}*/
			
			MsInfoQueryBean msInfoQueryBean = new MsInfoQueryBean();
			msInfoQueryBean.setFactoryNo(map.get("meterNo"));
			msInfoQueryBean.setMeterStatus(1);
			List<MsInfoDto> msList = msMapper.selectMsInfoList(msInfoQueryBean );
			if(StringUtils.isBlank(map.get("meterNo")) || msList==null || msList.size()==0 || meterNomap.get(map.get("meterNo"))!=null) {
				errorMsg=errorMsg+"水表编号不能为空或非在库状态;";
			}
			if(StringUtils.isNotBlank(meterNomap.get(map.get("meterNo")))) {
				errorMsg=errorMsg+"水表编号不能重复使用;";
			}else {
				meterNomap.put(map.get("meterNo"), "1");
			}
			if(msList!=null && msList.size()>0) {
				userInfo.setMeterNo(msList.get(0).getMeterNo());//
				userInfo.setMeterType(msList.get(0).getMeterType());
			}
			
			
			AdminAreaBean bean = new AdminAreaBean();
			//bean.setAreaNo(adminAreaDivi);
			bean.setFullName(map.get("clientContractAddr"));
			List<AdminAreaListBean> list = pmapper.queryList(bean);
			
			bean.setFullName(map.get("clientAddr"));
			List<AdminAreaListBean> list1 = pmapper.queryList(bean);
			AdminAreaListBean clientContractAddrId = new AdminAreaListBean(),
					clientAddrId=new AdminAreaListBean();
			
			if(list!=null && list.size()>0 && list1!=null && list1.size()>0) {
				clientContractAddrId=list.get(0);
				clientAddrId=list1.get(0);
			}else{
				errorMsg=errorMsg+"客户/装表地址格式不正确;";
			}
			userInfo.setClientContractAddr(clientContractAddrId.getId());
			userInfo.setClientContractAddrDetail(map.get("clientContractAddrDetail"));
			ctmInfo.setClientAddr(clientAddrId.getId());
			ctmInfo.setClientAddrDetail(map.get("clientAddrDetail"));
			
			userInfo.setSetupMeterAddr(clientContractAddrId.getFullName()+""+map.get("clientContractAddrDetail"));
			ctmInfo.setCtmAddr(clientAddrId.getFullName()+""+map.get("clientAddrDetail"));
			
			String setupMeterLocation = getKey(CTL, map.get("setupMeterLocation"));
			if(setupMeterLocation!=null) {
				userInfo.setSetupMeterLocation(setupMeterLocation);//装表位置
			}

			userInfo.setVirtualDesignFormulas(map.get("virtualDesignFormulas"));

			String meterUse = getKey(CMC, map.get("meterUse"));
			if(meterUse!=null) {
				userInfo.setMeterUse(meterUse);//水表用途
			}else {
				errorMsg=errorMsg+"水表用途不存在;";
			}
			String useWaterObject = getKey(UWS, map.get("useWaterObject"));
			if(useWaterObject!=null) {
				userInfo.setUseWaterObject(useWaterObject);//用水对象
			}else {
				errorMsg=errorMsg+"用水对象不存在;";
			}
			
			userInfo.setSetupMeterDate(map.get("setupMeterDate"));
			// 获取value值selectPrefStrategyByname
			if (!StringUtils.isBlank(map.get("useWaterType"))) {
				WaterTypeBean waterType = waterTypeMapper.findWaterTypeByName(map.get("useWaterType"));
				if(waterType!=null) {
					userInfo.setUseWaterType(waterType.getId());
					userInfo.setUseWaterTypeName(waterType.getWaterTypeName());
				}else {
					errorMsg=errorMsg+"用水类型不存在;";
				}
			}else {
				errorMsg=errorMsg+"用水类型不能为空;";
			}

			userInfo.setMeterBjxs(map.get(("meterBjxs")));//表井形式
			userInfo.setMeterBjms(map.get("meterBjms"));//表井模式


//			//表井位置
//			String meterBjwz = getKey(BJWZ, map.get("meterBjwz"));
//			if(meterBjwz!=null) {
//				userInfo.setMeterBjwz(meterBjwz);//表井位置
//			}else {
//				errorMsg=errorMsg+"表井位置不存在;";
//			}
//
//			//表井形式
//			String meterBjxs = getKey(BJXS, map.get("meterBjxs"));
//			if(meterBjxs!=null) {
//				userInfo.setMeterBjxs(meterBjxs);//表井形式
//			}else {
//				errorMsg=errorMsg+"表井形式不存在;";
//			}
//
//			//表井模式
//			String meterBjms = getKey(BJMS, map.get("meterBjms"));
//			if(meterBjms!=null) {
//				userInfo.setMeterBjms(meterBjms);//表井模式
//			}else {
//				errorMsg=errorMsg+"表井模式不存在;";
//			}
			// 获取优惠策略名称
			if (!StringUtils.isEmpty(map.get("prefStrategyId"))) {
				PrefStrategyBean prefStrategy = prefStrategyMapper.selectPrefStrategyByname(map.get("prefStrategyId"));
				if(prefStrategy!=null) {
					userInfo.setPrefStrategyId(prefStrategy.getId());
				}else {
					errorMsg=errorMsg+"优惠策略不存在;";
				}
			}
			// 判断装表日期格式是否合法
			if (!StringUtils.isEmpty(map.get("setupMeterDate"))) {
				if(!isValidDate(map.get("setupMeterDate"))) {
					errorMsg=errorMsg+"装表日期格式不合法;";
				}
			}
			// 判断用户组编号是否存在
			if (StringUtils.isNotEmpty(map.get("userGroupNo"))) {
				UserGroupMapper userGroupMapper = factory.getMapper(UserGroupMapper.class);
				if(null !=userGroupMapper.selectOneByUserGroupNo(map.get("userGroupNo"))) {
					userInfo.setUserGroupNo(map.get("userGroupNo"));
				}else {
					errorMsg=errorMsg+"用户组编号不存在;";
				}
			}
			userInfo.setPrefCertNo(map.get("prefCertNo"));
			userInfo.setPrefBeginDate(map.get("prefBeginDate"));
			userInfo.setPrefEndDate(map.get("prefEndDate"));
			userInfo.setLadderPersonNum(4);//默认用水人口为4
            userInfo.setMeterSite(map.get("meterSite"));

			//ic卡号和表号
            userInfo.setMiicno(map.get("MIICNO"));
            userInfo.setMiljfje(map.get("MILJFJE"));

			//水司账户
			userInfo.setBankSubAccount(map.get("bankSubAccount"));
			userInfo.setBankCode(map.get("bankCode"));
			//判断定额水量是否为空
			if (StringUtils.isNotEmpty(map.get("quotaWater"))) {
				userInfo.setQuotaWater(Integer.valueOf(map.get("quotaWater")));
			}else{
				userInfo.setQuotaWater(0);
			}
			userInfo.setRealEstateNo(map.get("realEstateNo"));

			
			// 校验，TODO Auto-generated method stub
			// 校验水表编号
			if(StringUtils.isEmpty(userInfo.getMeterNo())) {
				errorMsg = errorMsg+"水表编号不能为空;";
			}/*else if ("2".equals(userInfo.getMeterType())) {
				if(StringUtils.isEmpty(userInfo.getVirtualDesignFormulas())) {
					errorMsg = errorMsg+"虚拟表计算公式不能为空;";
				}
				//获取公式中的用户编号
				List<String> userNos=Tools.getUserNoFromFormulas(userInfo.getVirtualDesignFormulas());
				for(String userNo:userNos) {
					//判断公式中用户编号是否为监控表
					UserBean formulasUserNo=userMapper.getUserInfoByCode(userNo, UserBean.USER);
					if(formulasUserNo==null||!"3".equals(formulasUserNo.getMeterUse())) {
						errorMsg = errorMsg+"虚拟公式中的用户的水表用途不是监控表;";
					}
				}
			}*/

			userInfo.setCreateInfo(userInfoBean);
			userInfo.setCtmNo(ctmInfo.getCtmNo());
			userInfo.setStatus("1");
			userInfo.setLockFlag(0);
			userInfo.setOpenDate(Tools.getCurrentDate());
			userInfo.setAccountNo(accountInfo.getAccountNo());
			
			userOpenInfo.setCreateInfo(userInfoBean);
			userOpenInfo.setUserAccountTempId(accountInfo.getId());
			userOpenInfo.setUserCtmTempId(ctmInfo.getId());
			userOpenInfo.setUserInfoTempId(userInfo.getId());
			
			
			//去掉 mapper.userOpenAdd(userOpenInfo);使用list的方式插入数据库

			// 获取开户信息
			//accountMapper.accountInfoAdd(accountInfo,AccountInfoBean.ACCOUNTTEMP );
			//ctmMapper.ctmInfoAdd(ctmInfo, CtmInfoBean.CTMTEMP);
			//userMapper.userInfoAdd(userInfo, UserBean.USERTEMP);
			Map<String, String> mapData = new HashMap<String, String>();
			mapData.put("id", userOpenInfo.getId());
			mapData.put("ctmNo", ctmInfo.getCtmNo());
			mapData.put("accountNo", userInfo.getAccountNo());
			mapData.put("userNo", userInfo.getUserNo());
			mapData.put("ctmName", ctmInfo.getCtmName());
			//mapData.put("bookNo", userInfo.getBookNo());
			mapData.put("businessAreaName", map.get("businessArea"));
			mapData.put("setupMeterAddr", userInfo.getSetupMeterAddr());
			mapData.put("setupMeterDate", map.get("setupMeterDate"));
			if(errorMsg.length()==0) {
				//校验通过
				openTempList.add(userOpenInfo);
				accountList.add(accountInfo);
				ctmList.add(ctmInfo);
				//冗余字段设置
				OpenUserAdd.ctmInfoToUserInfo(ctmInfo,userInfo);
				userList.add(userInfo);
				returnMap.add(mapData);
			}else {
				//校验失败
				map.put("errorMsg", errorMsg);
				map.put("id",Tools.getObjectId());
				errorMap.add(map);
			}
		}
		//插入数据库
		try {
			//插入详情关联列表数据
			if(openTempList.size()>0) {
				mapper.userOpenTempAddList(openTempList);
				accountMapper.accountInfoAddList(accountList, 2);
				ctmMapper.ctmInfoAddList(ctmList, 2);
				userMapper.userInfoAddList(userList, 2);
			}
			
			//先删除再插入错误数据
			mapper.DeleteImportError();
			Map<String,Object> resultMap = new HashMap<String, Object>();
			
			if(errorMap.size()>0) {
				resultMap.put("flag", 1);
				mapper.insertOpenImportError(errorMap);
			}else {
				resultMap.put("flag", 0);
			}
			
			resultMap.put("returnMap", returnMap);
			
			MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", Map.class);
			info.setData(resultMap);
			return info;
		}catch (Exception e) {
			logger.error("开户失败", e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "开户失败", void.class);
		}
	}

	/**
	 * 判断字符串是否为合法的日期格式
	 * @param dateStr 待判断的字符串
	 * @return
	 */
	public static boolean isValidDate(String dateStr){
		//判断结果 默认为true
		boolean judgeresult=true;
		//1、首先使用SimpleDateFormat初步进行判断，过滤掉注入 yyyy-01-32 或yyyy-00-0x等格式
		//此处可根据实际需求进行调整，如需判断yyyy/MM/dd格式将参数改掉即可
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try{
			//增加强判断条件，否则 诸如2022-02-29也可判断出去
			format.setLenient(false);
			Date date =format.parse(dateStr);
		}catch(Exception e){
			judgeresult=false;
		}
		//由于上述方法只能验证正常的日期格式，像诸如 0001-01-01、11-01-01，10001-01-01等无法校验，此处再添加校验年费是否合法
		String yearStr=dateStr.split("-")[0];
		if(yearStr.startsWith("0")||yearStr.length()!=4){
			judgeresult=false;
		}
		return judgeresult;
	}
	public static String getKey(Map<String,String> map, String value){
		for (Map.Entry<String, String> entry : map.entrySet()) {
			if(value!=null && value.equals(entry.getValue())) {
				return entry.getKey();
			}
		}
		return null;
		
	}
}
